<template>
  <div class="fixed inset-0 bg-black bg-opacity-50 z-50 flex justify-end" v-if="show">
    <div class="bg-gray-900 w-full max-w-md h-full overflow-y-auto animate-slide-in">
      <!-- 设置面板头部 -->
      <div class="p-4 border-b border-gray-700 flex justify-between items-center sticky top-0 bg-gray-900 z-10">
        <h2 class="text-xl font-bold">设置</h2>
        <button @click="close" class="p-2 text-gray-400 hover:text-white">
          <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
          </svg>
        </button>
      </div>
      
      <!-- 设置面板内容 -->
      <div class="p-4">
        <!-- 导航标签 -->
        <div class="flex border-b border-gray-700 mb-4">
          <button 
            v-for="tab in tabs" 
            :key="tab.id"
            @click="activeTab = tab.id"
            :class="[
              'px-4 py-2 font-medium',
              activeTab === tab.id ? 'border-b-2 border-[#8153ff] text-[#8153ff]' : 'text-gray-400 hover:text-white'
            ]"
          >
            {{ tab.name }}
          </button>
        </div>
        
        <!-- 标签内容 -->
        <div class="space-y-6">
          <!-- 模型管理 -->
          <div v-if="activeTab === 'models'">
            <ModelSelector 
              v-if="!showModelForm" 
              @select-model="handleSelectModel"
              @open-model-config="showModelForm = true"
            />
            <ModelConfigForm 
              v-else 
              :model="editingModel"
              :apiKeys="apiKeys"
              @save="handleSaveModel"
              @cancel="showModelForm = false"
              @add-api-key="handleAddApiKey"
            />
          </div>
          
          <!-- API管理 -->
          <div v-if="activeTab === 'api'">
            <ApiKeyManager 
              :apiKeys="apiKeys"
              @update:apiKeys="updateApiKeys"
            />
          </div>
          
          <!-- 通用设置 -->
          <div v-if="activeTab === 'general'">
            <div class="bg-gray-800 rounded-lg p-4">
              <h3 class="text-lg font-medium mb-4">通用设置</h3>
              
              <div class="space-y-4">
                <!-- 外观主题 -->
                <div>
                  <label class="block text-sm text-gray-400 mb-2">外观主题</label>
                  <div class="flex space-x-2">
                    <button 
                      @click="setTheme('dark')"
                      :class="[
                        'px-3 py-2 rounded-md flex items-center',
                        theme === 'dark' ? 'bg-[#8153ff] text-white' : 'bg-gray-700 text-gray-300'
                      ]"
                    >
                      <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 mr-1" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M20.354 15.354A9 9 0 018.646 3.646 9.003 9.003 0 0012 21a9.003 9.003 0 008.354-5.646z" />
                      </svg>
                      深色
                    </button>
                    <button 
                      @click="setTheme('light')"
                      :class="[
                        'px-3 py-2 rounded-md flex items-center',
                        theme === 'light' ? 'bg-[#8153ff] text-white' : 'bg-gray-700 text-gray-300'
                      ]"
                    >
                      <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 mr-1" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 3v1m0 16v1m9-9h-1M4 12H3m15.364 6.364l-.707-.707M6.343 6.343l-.707-.707m12.728 0l-.707.707M6.343 17.657l-.707.707M16 12a4 4 0 11-8 0 4 4 0 018 0z" />
                      </svg>
                      浅色
                    </button>
                    <button 
                      @click="setTheme('system')"
                      :class="[
                        'px-3 py-2 rounded-md flex items-center',
                        theme === 'system' ? 'bg-[#8153ff] text-white' : 'bg-gray-700 text-gray-300'
                      ]"
                    >
                      <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 mr-1" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9.75 17L9 20l-1 1h8l-1-1-.75-3M3 13h18M5 17h14a2 2 0 002-2V5a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z" />
                      </svg>
                      跟随系统
                    </button>
                  </div>
                </div>
                
                <!-- 语言设置 -->
                <div>
                  <label class="block text-sm text-gray-400 mb-2">语言</label>
                  <select 
                    v-model="language"
                    class="w-full bg-gray-700 border border-gray-600 rounded px-3 py-2 focus:outline-none focus:ring-2 focus:ring-[#8153ff] focus:border-transparent"
                  >
                    <option value="zh-CN">中文(简体)</option>
                    <option value="en-US">English</option>
                    <option value="ja-JP">日本語</option>
                    <option value="ko-KR">한국어</option>
                  </select>
                </div>
                
                <!-- 发送方式 -->
                <div>
                  <label class="block text-sm text-gray-400 mb-2">消息发送方式</label>
                  <div class="flex items-center justify-between p-3 bg-gray-700 rounded-lg">
                    <div>
                      <div class="font-medium">按Enter键发送消息</div>
                      <div class="text-xs text-gray-400">使用Shift+Enter换行</div>
                    </div>
                    <label class="relative inline-flex items-center cursor-pointer">
                      <input type="checkbox" v-model="enterToSend" class="sr-only peer">
                      <div class="w-11 h-6 bg-gray-600 rounded-full peer peer-checked:bg-[#8153ff] peer-checked:after:translate-x-full after:content-[''] after:absolute after:top-0.5 after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all"></div>
                    </label>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, defineProps, defineEmits, watch, onMounted } from 'vue';
import ModelSelector from './ModelSelector.vue';
import ApiKeyManager from './ApiKeyManager.vue';
import ModelConfigForm from './ModelConfigForm.vue';

const props = defineProps({
  show: {
    type: Boolean,
    default: false
  }
});

const emit = defineEmits(['close', 'apiKeys-update']);

// 设置标签
const tabs = [
  { id: 'models', name: '模型管理' },
  { id: 'api', name: 'API密钥' },
  { id: 'general', name: '通用设置' }
];

// 当前激活的标签
const activeTab = ref('models');

// 主题设置
const theme = ref('dark');
const language = ref('zh-CN');
const enterToSend = ref(true);

// 模型配置表单控制
const showModelForm = ref(false);
const editingModel = ref(null);

// API密钥数据 - 使用从localStorage获取的数据初始化，如果没有则使用空数组
const apiKeys = ref([]);

// 在组件挂载时加载已保存的API配置
onMounted(() => {
  // 从localStorage获取API配置
  const apiConfigsStr = localStorage.getItem('apiConfigs');
  if (apiConfigsStr) {
    try {
      apiKeys.value = JSON.parse(apiConfigsStr);
      console.log('从localStorage加载的API配置:', apiKeys.value);
    } catch (e) {
      console.error('解析API配置失败:', e);
      // 解析失败则使用空数组
      apiKeys.value = [];
    }
  }
});

// 监听显示状态，重置表单
watch(() => props.show, (newVal) => {
  if (newVal) {
    // 打开面板时，重置为模型管理标签
    activeTab.value = 'models';
    showModelForm.value = false;
  }
});

// 关闭设置面板
const close = () => {
  emit('close');
};

// 设置主题
const setTheme = (newTheme) => {
  theme.value = newTheme;
  // 这里可以实现实际的主题切换逻辑
  console.log('Theme changed to:', newTheme);
};

// 处理选择模型
const handleSelectModel = (model) => {
  // 这里可以实现选择模型的逻辑
  console.log('Selected model:', model);
  
  // 查找是否有关联的API配置
  const apiConfig = apiKeys.value.find(key => key.provider === model.id.toString() || key.id === model.id.toString());
  if (apiConfig) {
    // 如果找到了关联的API配置，将其设置为当前选中的配置
    localStorage.setItem('selectedApiConfigId', apiConfig.id);
  }
};

// 处理保存模型
const handleSaveModel = (formData) => {
  console.log('Saving model:', formData);
  
  // 生成唯一ID
  const modelId = Date.now().toString();
  
  // 创建新的API配置对象
  const newApiConfig = {
    id: modelId,
    name: formData.name,
    provider: formData.provider,
    providerName: formData.providerName,
    key: '', // 将从关联的API密钥获取
    endpoint: '', // 将从关联的API密钥获取
    modelName: formData.modelName || formData.modelId, // 确保modelName存在
    apiKeyId: formData.apiKeyId,
    iconText: formData.iconText,
    iconBg: formData.iconBg,
    description: formData.description
  };
  
  // 如果指定了API密钥，从中获取key和endpoint
  if (formData.apiKeyId) {
    const apiKey = apiKeys.value.find(key => key.id === formData.apiKeyId);
    if (apiKey) {
      newApiConfig.key = apiKey.key;
      newApiConfig.endpoint = apiKey.endpoint;
    }
  }
  
  // 添加到API配置列表
  apiKeys.value.push(newApiConfig);
  
  // 保存到localStorage
  localStorage.setItem('apiConfigs', JSON.stringify(apiKeys.value));
  
  // 通知父组件
  emit('apiKeys-update', apiKeys.value);
  
  // 关闭表单
  showModelForm.value = false;
};

// 处理添加自定义API密钥
const handleAddApiKey = (newApiKey) => {
  console.log('Adding new API key:', newApiKey);
  apiKeys.value.push(newApiKey);
};

// 更新API密钥并传递到父组件
const updateApiKeys = (newApiKeys) => {
  console.log('SettingsPanel接收到API密钥更新:', newApiKeys);
  apiKeys.value = newApiKeys;
  
  // 保存到localStorage
  localStorage.setItem('apiConfigs', JSON.stringify(newApiKeys));
  
  // 发送到父组件
  emit('apiKeys-update', newApiKeys);
};
</script>

<style scoped>
.animate-slide-in {
  animation: slide-in 0.3s ease-out;
}

@keyframes slide-in {
  from { transform: translateX(100%); }
  to { transform: translateX(0); }
}
</style> 